package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-10-27 10:34
 */
@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public List<SearchArticleVo> search(UserSearchDto dto) {

        try{
            //1.拼接条件，查询条件
            SearchRequest request = new SearchRequest("app_info_article");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //boolQuery must should filter must_not
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //a.分词查询
            boolQueryBuilder.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title").field("content").defaultOperator(Operator.OR)
            );
            //b.时间查询
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime")
                    .lt(dto.getMinBehotTime().getTime()));
            searchSourceBuilder.query(boolQueryBuilder);
            //排序
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);
            //分页
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(dto.getPageSize());

            //高亮
            searchSourceBuilder.highlighter(new HighlightBuilder().requireFieldMatch(true)
                    .field("title").preTags("<font style='color: red; font-size: inherit;'>")
                    .postTags("</font>")
            );

            //2.调用接口进行查询
            request.source(searchSourceBuilder);
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            //3.封装返回结果
            //基础数据封装
            SearchHit[] hits = search.getHits().getHits();
            List<SearchArticleVo> vos = new ArrayList<>();
            for (SearchHit hit : hits) {
                String source = hit.getSourceAsString();
                SearchArticleVo searchArticleVo = JSON.parseObject(source, SearchArticleVo.class);
                vos.add(searchArticleVo);

                searchArticleVo.setH_title(searchArticleVo.getTitle());

                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if(CollectionUtils.isNotEmpty(highlightFields)){
                    HighlightField title = highlightFields.get("title");
                    if(title != null){
                        Text[] fragments = title.getFragments();
                        if(fragments != null && fragments.length > 0){
                            Text fragment = fragments[0];
                            String string = fragment.string();
                            searchArticleVo.setH_title(string);
                        }
                    }
                }
            }
            //高亮数据

            return vos;
        }catch (Exception e){
            log.error("搜索异常",e);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"搜索功能出现错误");
        }

    }

    @Override
    public void createArticle(SearchArticleVo searchArticleVo) {
        IndexRequest request = new IndexRequest("app_info_article")
                .id(searchArticleVo.getId().toString()).source(JSON.toJSONString(searchArticleVo), XContentType.JSON);
        try {
            restHighLevelClient.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("添加数据到es失败" + searchArticleVo.toString(),e);
        }
    }
}
